debug("Ready now.\n**********************************");
var Config = {
    portSocket: 10000,
    portHttp:9999,
    secret:"Hamm.cn",
};
var websocket = require("nodejs-websocket"),
crypto = require('crypto'),
http = require('http'),
https = require('https');
var webSocketServer = websocket.createServer(function(conn) {
    var query = login(conn.path);
    if (!query) {
        debug("客户端连接失败(登录失败)");
        conn.close();
    }else{
        debug("客户端连接成功 "+query.account);
    }
    conn.on("close",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("error",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("text",
    function(msg) {
    });
});
webSocketServer.listen(Config.portSocket);
debug("服务启动成功(" + Config.portSocket.toString() + ")Websocket");
checkConnection();
function checkConnection() {
    setTimeout(function() {
        debug("当前在线连接数：(" + webSocketServer.connections.length + ")");
        sendOnlineList();
        checkConnection();
    },
    10000);
}

function sendOnlineList(){
    var url = 'https://bbbug.com/api/chat/getOnLineList';
    https.get(url,function(res){
        var dataString="";
        res.on("data",function(data){
            dataString+=data;
        });
        res.on("end",function(){
            webSocketServer.connections.forEach(function(conn) {
                conn.sendText(JSON.stringify({
                    msg:{
                        type:"online",
                        data:dataString
                    }
                }));
            });
        });
    });
}

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var httpServer = http.createServer(function(req, res) {
    if (req.method.toUpperCase() == 'POST') {
        res.writeHead(200, {
            'Content-Type': 'application/json;charset=utf-8'
        });
        var postData = ''; 
        req.on('data', function(chunk){    
            postData += chunk;
        });
        req.on('end', function(){    
            postData = querystring.parse(postData);
            if(postData.token=='dqwhohigoqwhoghqohgoqwhgioqowghqiowhgoqhwgoqhw'){
                webSocketServer.connections.forEach(function(conn) {
                    var query = new QueryString(conn.path);
                    if (query.channel == postData.channel) {
                        conn.sendText(postData.msg);
                    }
                });
            }
            res.end();
        });
    }else if(req.method.toUpperCase()=='GET'){
        res.writeHead(200, {
            'Content-Type': 'application/json;charset=utf-8'
        });
        var onlineList = [];
        webSocketServer.connections.forEach(function(conn) {
            var query = new QueryString(conn.path);
            onlineList.push(query.account);
        });
        res.end(JSON.stringify(onlineList));
    }else{
        res.writeHead(403, {
            'Content-Type': 'application/json;charset=utf-8'
        });
        res.end();
    }
});
httpServer.listen(Config.portHttp);
debug("Web服务{" + Config.portHttp + "}启动成功!");


function getTime() {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hours + ":" + minutes + ":" + seconds;
}

function debug(message) {
    console.log(getTime()+" : "+message);
}

function login(url) {
    var query = new QueryString(url);
    if (sha1("account" + query.account + "channel" + query.channel+ Config.secret) == query.ticket) {
        return query;
    } else {
        return false;
    }
}

function QueryString(url) {
    var name, value;
    url = url.replace("/?", "");
    var arr = url.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            this[name] = value;
        }
    }
}

function getTimeStamp(){
    return Date.parse(new Date())/1000;
}

function sha1(str) {
    var sha1 = crypto.createHash("sha1"); //定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    sha1.update(str);
    var res = sha1.digest("hex"); //加密后的值d
    return res;
}
